using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace HerenityCode.Reference
{
    namespace GO
    {
        /// <summary>
        /// Description:通过各种方法获取游戏对象
        /// Author:哒先生
        /// Date:2024年10月9日18:02:57
        /// </summary>
        public class GetGameObject : MonoBehaviour
        {
            /// <summary>
            /// 放在Update中调用，获取鼠标点击位置的GameObject，返回GameObjectMessage
            /// </summary>
            /// <param name="tag">游戏物体的tag，如果为“”则表示任何物体都可以获取</param>
            /// <returns></returns>
            public static GameObjectMessage MouseClickObject(string tag)
            {
                GameObjectMessage msg = new GameObjectMessage();
                if (Input.GetMouseButtonDown(0))
                {
                    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                    RaycastHit hit;
                    if (Physics.Raycast(ray, out hit))
                    {
                        if (hit.collider.tag == tag || tag == "")
                        {
                            msg.mousePos = Input.mousePosition;
                            msg.TarGO = hit.collider.gameObject;
                            msg.oriScreenPos = Camera.main.WorldToScreenPoint(msg.TarGO.transform.position);
                            msg.tempObjectPosition = msg.TarGO.transform.position;
                        }
                        else
                        {
                            Debug.Log("没有符合条件的物体");
                        }
                    }
                    else
                    {
                        Debug.Log("未检测到碰撞");
                    }
                }

                return msg;
            }
            
            public static List<T> GetAllComponentsInChildren<T>(GameObject go) where T : Component
            {
                List<T> components = new List<T>();
                // 获取当前物体上的组件
                T[] currentComponents = go.GetComponents<T>();
                components.AddRange(currentComponents);

                // 遍历所有子物体
                foreach (Transform child in go.transform)
                {
                    // 递归调用以获取子物体上的组件
                    components.AddRange(GetAllComponentsInChildren<T>(child.gameObject));
                }

                return components;
            }
            
        }
        
        

        /// <summary>
        /// 获取物体相关的信息
        /// </summary>
        public class GameObjectMessage
        {
            public GameObject TarGO;

            public Vector3 mousePos;
            public Vector3 oriScreenPos;
            public Vector3 tempObjectPosition;
        }
    }
}
